<template>
  <div class="app-container">
    <!-- <el-upload
      ref="upload"
      class="upload-demo"
      action="/upload/one"
      :multiple="false"
      :limit="1"
      name="file"
      :file-list="fileList"
    >
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <div slot="tip" class="el-upload__tip">支持UTF-8-BOM编码格式csv、xlsx文件</div>
    </el-upload> -->
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" :do-upload="doUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import request from '@/utils/request'

export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: '文件大小不要超过1M（这个值可以改）.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
    },
    doUpload(file) {
      console.log(file)
      const param = new FormData() // 创建form对象
      param.append('file', file) // 通过append向form对象添加数据
      param.append('name', file.name) // 通过append向form对象添加数据
      // param.append('name', 'ytl') // 添加form表单中其他数据
      const config = {
        headers: { 'Content-Type': 'multipart/form-data' }
      }
      request({
        url: '/upload/one',
        method: 'post',
        data: param,
        config
      }).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '上传成功',
            type: 'success'
          })
        }
        console.log(res)
      })
    }
  }
}
</script>
